<?php
namespace Application\Api\Controller;

class X extends Base
{

    public function sendAgentAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'dry_phone') || notSetOrEmpty($data, 'dry_code') || notSetOrEmpty($data, 'dry_main_product') || notSetOrEmpty($data, 'dry_main_product_spec') || notSetOrEmpty($data, 'device') || notSetOrEmpty($data, 'token')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $phone = $data['dry_phone'];
        $code = $data['dry_code'];
        $mainProduct = $data['dry_main_product'];
        $mainProductSpec = $data['dry_main_product_spec'];
        $device = $data['device'];
        $token = $data['token'];
        //
        if(!isPhone($phone)){
            $this->sendFail('PARAMETER_ERROR', '手机号不正确');
            return false;
        }
        $serviceUser = $this->get(SERVICE_USER);
        if(!$serviceUser->validToken($device, $token)){
            $this->sendFail('TOKEN_ERROR');
            return false;
        }
        $userId = (int)parseUserCode($code);
        $user = $serviceUser->one($userId);
        if(empty($user)){
            $this->sendFail('PARAMETER_ERROR', '优惠码不正确');
            return false;
        }
        $user = $serviceUser->decrypt($user);
        if($user->dry_phone != $phone){
            $this->sendFail('PARAMETER_ERROR', '手机号和优惠码不匹配');
            return false;
        }
        $serviceProductAgent = $this->get(SERVICE_PRODUCTAGENT);
        if($serviceProductAgent->hasAgent($userId, $mainProduct, $mainProductSpec)){
            $this->sendFail('PARAMETER_ERROR', '所选代理已经发放');
            return false;
        }
        $startTime = getDateTimeStd(getTimestamp());
        $endTime = THE_DATE_TIME_END_LONG;
        $serviceProductAgent->addAgent($userId, $mainProduct, $mainProductSpec, $startTime, $endTime);
        $this->sendSuccess();
    }

}